package com.xiaoshuidi.cloud.module.contract.util.pdf;

import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Image;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.pdf.PdfWriter;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.List;

/**
 * 图片转pdf工具类
 */
public class ImgToPdfUtil {
    public static ByteArrayOutputStream Pdf(List<Image> images) {
        //new一个pdf文档
        Document doc = new Document(PageSize.A4, 0, 0, 0, 0);
        ByteArrayOutputStream baos = null;
        try {
            baos = new ByteArrayOutputStream();
            //pdf写入
            PdfWriter.getInstance(doc, baos);
            doc.open();//打开文档
            for (int i = 0; i < images.size(); i++) {  //循环图片List，将图片加入到pdf中
                doc.newPage();  //在pdf创建一页
                Image png1 = images.get(i); //通过文件路径获取image
                float heigth = png1.getHeight();
                float width = png1.getWidth();
                int percent = getPercent2(heigth, width);
                png1.setAlignment(Image.MIDDLE);
                png1.scalePercent(percent + 3);// 表示是原来图像的比例;
                doc.add(png1);
            }
        } catch (DocumentException e) {
            e.printStackTrace();
        } finally {
            if (doc != null) {
                doc.close();
            }
            if (baos != null) {
                try {
                    baos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }


        return baos; //反回文件输出流
    }

    public static int getPercent(float h, float w) {
        int p = 0;
        float p2 = 0.0f;
        if (h > w) {
            p2 = 297 / h * 100;
        } else {
            p2 = 210 / w * 100;
        }
        p = Math.round(p2);
        return p;
    }

    public static int getPercent2(float h, float w) {
        int p = 0;
        float p2 = 0.0f;
        p2 = 530 / w * 100;
        p = Math.round(p2);
        return p;
    }

    /**
     * @Description: 通过图片路径及生成pdf路径，将图片转成pdf
     * @Author: zd
     * @Date: 2019/9/29
     */
/*    public void imgOfPdf(String filepath, List<Image> images) {
        try {
            String pdfUrl =  filepath;  //输出pdf文件路径
            File file = this.Pdf(images, pdfUrl);//生成pdf
            file.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        ImgToPdfUtil img = new ImgToPdfUtil();
        List<Image> testPdf = PdfToImgUtil.pdf3png("E:\\testPdf", "20210603b");
        img.imgOfPdf("E:\\testPdf\\newtest2.pdf",testPdf);
    }*/
}

